<?php
class Database
{
	private $link;
	
	function __construct($server, $database, $username, $password)
	{
		$this->link = mysql_connect($server, $username, $password);
		if ($this->link)
		{
			mysql_select_db($database, $this->link);
		}
	}
	
	function __destruct()
	{
		if ($this->link)
		{
			mysql_close($this->link);
		}
	}
	
	public function insert($table, $arguments)
	{
		$query = '';
		$columns = '';
		$values = '';
		$query_result = false;
		
		// Build columns and values list
		foreach ($arguments as $key => $value)
		{
			$columns .= $key.',';
			
			if (is_int($value) ||
				is_float($value))
			{
				$values .= $value.',';
			}
			else if (is_string)
			{
				$values .= "'".$value."',";
			}
		}
		
		// Remove last , char
 		$columns = rtrim($columns, ',');
		$values = rtrim($values, ',');
		
		// Build query
		$query = 'INSERT INTO `'.$table.'` 
					('.$columns.')
					VALUES ('.$values.')';
		if (mysql_query($query, $this->link))
		{
			$query_result->{'insert_id'} = mysql_insert_id($this->link);
			$query_result->{'affected_rows'} = mysql_affected_rows($this->link);
		}
		
		return $query_result;
	}
	
	public function query($query)
	{
		$resultset = array();
		$result = mysql_query($query, $this->link);
		
		if ($result)
		{
			while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
			{
				$resultset[] = (object)$row;
			}
		}
		else
		{
			$message  = 'Invalid query: ' . mysql_error() . "\n";
			$message .= 'Whole query: ' . $query;
			die($message);
		}

		mysql_free_result($result);
		
		return $resultset;
	}
	
	public function update($query)
	{
		try
		{
			$result = mysql_query($query, $this->link);
		}
		catch (Exception $exception)
		{
			return $exception;
		}
		
		return $result;
	}
	
}
?>